package com.sky.wsp.sql.scanner.utils;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author wangshaopeng@talkweb.com.cn
 * @desccription 在此输入描述
 * @date 2024/11/13
 */
public class FileNameUtil {

    /**
     * 从全路径上截取文件名，例如：
     * d:/tmp/abc.jar ==> abc.jar
     * d:/tmp/dir/ ==> dir
     */
    public static String name(String path) {
        path = path.replaceAll("\\\\", "/");
        if (path.charAt(path.length() - 1) == '/') {
            path = path.substring(0, path.length() - 1);
        }
        path = path.substring(path.lastIndexOf('/') + 1);
        return path;
    }

    /**
     * 截取简单文件名，不带扩展名
     * d:/tmp/abc.jar ==> abc
     * abc.jar ==> abc
     * d:/tmp/dir/ ==> dir
     * dir/ ==> dir
     * dir ==> dir
     */
    public static String simpleName(String fullName) {
        String name = name(fullName);
        int dox = name.lastIndexOf(".");
        String simpleName = dox > 0 ? name.substring(0, dox) : name;
        return simpleName;
    }

    /**
     * 根据jar包文件名，截取前缀，作为过滤关键字
     */
    public static ArrayList<String> getIgnoresKeyByNames(List<String> jarNames) {
        Set<String> log = new HashSet<>();
        for (String name : jarNames) {
            String simpleName = FileNameUtil.simpleName(name);
            String key;
            int hrz = simpleName.indexOf('-');
            if (hrz <= 0) {
                hrz = simpleName.indexOf('.');
            }
            if (hrz <= 0) {
                key = simpleName;
            } else {
                key = simpleName.substring(0, hrz);
                if (key.length() < 3) {
                    // 太短了容易误伤
                    key = key + '-';
                }
            }
            log.add(key);
        }
        ArrayList<String> list = new ArrayList<>(log);
        list.sort(String::compareTo);
        return list;
    }


    /**
     * 前缀匹配
     */
    public static boolean prefixMatch(String name, Set<String> ignoreNames) {
        for (String ignoreName : ignoreNames) {
            if (name.startsWith(ignoreName)) {
                return true;
            }
        }
        return false;
    }

    public static void main(String[] args) {
        // 测试一下
        System.out.println(FileNameUtil.simpleName("d:/tmp/abc.jar"));
        System.out.println(FileNameUtil.simpleName("abc.jar"));
        System.out.println(FileNameUtil.simpleName("d:/tmp/dir/"));
        System.out.println(FileNameUtil.simpleName("d:/tmp/dir"));
        System.out.println(FileNameUtil.simpleName("dir/"));
        System.out.println(FileNameUtil.simpleName("dir"));
        System.out.println(FileNameUtil.simpleName("/dir"));
    }
}
